#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <FS.h>
#define html_file_name "/index.html"

#define DNS_PORT   53            //默认DNS设置端口为53

bool relay_statu = 0;

IPAddress apIP(192, 168, 1, 1);
DNSServer dnsServer;
ESP8266WebServer webServer(80);

void(* resetFunc) (void) = 0;
void web_page(void)
{
  Serial.println("main page !!!!");
  char s[30];
  memset(s,0x30,29);
  s[29]=0;
  Serial.print(s);
  if(SPIFFS.exists(html_file_name))
  {
    File file = SPIFFS.open(html_file_name, "r"); 
    webServer.streamFile(file, "text/html");
    file.close();
  }
  else
  {
    webServer.send(404,"text/plain","webFile don't exist !!!");
  }      
}


void callback_page(void)
{
  webServer.send(200, "text/plane","success!!!");
  String temp  = webServer.arg(0);
  if(temp=="ON")       {relay_statu = 1;digitalWrite(0,0);}
  else if(temp=="OFF") {relay_statu = 0;digitalWrite(0,1);}
  else if(temp=="RESET")resetFunc();
  Serial.print(temp);
  char s[30];
  memset(s,0x30,29);
  s[29]=0;
  Serial.print(s);
}

void setup() {
  // put your setup code here, to run once:
  SPIFFS.begin();
  Serial.begin(9600);
  WiFi.mode(WIFI_AP);
  pinMode(0,OUTPUT);
  WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
  WiFi.softAP("网页控制继电器");

    // 设置DNS服务的TTL数值为300
  dnsServer.setTTL(300);
  // 启动特定域名的DNS服务器
  dnsServer.start(DNS_PORT, "www.8266.com", apIP);
  
  //设置服务器页面信息
  webServer.on("/",web_page);
  webServer.onNotFound(callback_page);

  webServer.begin(); //启动web服务器

  char i = 5;
  while(i--)
  {
    digitalWrite(0,1);
    delay(200);
    digitalWrite(0,0);
    delay(200);
  }
  digitalWrite(0,1);
}

void loop() {
  // put your main code here, to run repeatedly:
    dnsServer.processNextRequest();//处理DNS请求服务
    webServer.handleClient();
}
